package com.kdg.thread.consurrenttest.threadpool;

import java.security.acl.LastOwnerException;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * @author kdg
 * @description:
 * @date 2018/5/16.
 */
public class ForkJoinTest extends RecursiveTask<Long> {

    private static final int THRESHOLD = 10000;
    private long start;
    private long end;

    public ForkJoinTest(long start, long end) {
        this.start = start;
        this.end = end;
    }

    public static void main(String[] args) {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTest forkJoinTest = new ForkJoinTest(0,20000L);
        ForkJoinTask<Long> submit = forkJoinPool.submit(forkJoinTest);
        try {
            Long aLong = submit.get();
            System.out.println(aLong);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected Long compute() {
        long sum=0;
        boolean canCompute = (end - start)<THRESHOLD;
        if(canCompute){
            for (long i=start;i<=end;i++){
                sum += i;
            }
        }else{
            //分成100个小任务
            long step = (start+end)/100;
            ArrayList<ForkJoinTest> forkJoinTests = new ArrayList<>();
            long pos = start;
            for(int i=0;i<100;i++){
                long lastOne = pos+step;
                if(lastOne > end){
                    lastOne = end;
                }
                ForkJoinTest forkJoinTest = new ForkJoinTest(pos, lastOne);
                pos += step + 1;
                forkJoinTests.add(forkJoinTest);
                forkJoinTest.fork();
            }
            for(ForkJoinTest t:forkJoinTests){
                sum += t.join();
            }
        }
        return sum;
    }
}
